package com.msb.bf;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.io.IOException;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: zhaoyi
 * @create: 2020-05-11 11:01
 * @description:
 **/

public class ThreadPoolExecutorTest {

    public static void main(String[] args) throws InterruptedException {

        int i1 = Runtime.getRuntime().availableProcessors();
        System.out.println(i1);

        AtomicInteger index = new AtomicInteger();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 5, 60L, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                new ThreadFactoryBuilder().setNameFormat("测试线程").build(),
                (Runnable r, ThreadPoolExecutor executor) -> {
                    BlockingQueue<Runnable> queue = executor.getQueue();
                    if (queue.size() < 10) {
                        //说明空闲了
                        System.out.println("说明空闲了尝试再次执行下" + r);
                        executor.submit(r);
                    } else {
                        //写入日志，数据库
                        System.out.println("线程池满了 任务丢失。。。" + r);
                    }
                });


        for (int i = 0; i < 30; ++i) {
            threadPoolExecutor.submit(() -> {
                Thread.sleep(8000);
                System.out.println("getActiveCount "+threadPoolExecutor.getActiveCount());
                System.out.println(threadPoolExecutor.getQueue().size());
                index.getAndIncrement();
                return "aa";
            });
            Thread.sleep(1000);
        }


       /* for (int i = 0; i < 10; ++i) {
            threadPoolExecutor.submit(() -> {
                System.out.println("run....");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            });
        }*/


        Thread.sleep(10000);

        System.out.println(index.get());


    }

}
